﻿
// ------------------------------------------------------------------
// FileName	：	CodeNameSelect.js
// Remark	：	代码选择
// ------------------------------------------------------------------
// VERSION		AUTHOR		DATE			CONTENT
// 1.0			席吉波	    2010-05-21	    创建
// 修改日志
// 1 修改人 席吉波，修改日期 2011-01-12
//   修改内容：当控件为ReadOnly时，隐藏Textbox，并用span来显示数据
// 2 修改人 席吉波，修改日期 2011-05-24
//   修改内容：新增OnSeletedComplete属性，此属性为客户端需要执行的方法
//             当此属性不为空时，会调用此方法，并传入一个Json参数
//             参数格式为：{Code:'',Name:''},使用者需先反序列化该参数
//             然后您就可以为所欲为了 
// 3 修改人 席吉波，修改日期 2011-12-26
//   修改内容：新增多项选择功能，需将控件的MutiSelecte属性设置为true
//             此次修改的地方较多，改动较大，但不影响之前的使用。 
// 4 修改人 席吉波，修改日期 2011-12-26  
//   修改内容：为兼容徐侠君在2011-05-24修改的参数名称，
//             特在以下几个方法中将参数做了修改
//             A: _invokeSingle()  
//             B: _invoke1()
//             C:_onTimerTick()
// 5 修改日期：2012-03-01
//   修改内容：将样式修改为Bing搜索框风格，并已考虑MutiSelecte时各HTML
//             元素的位置变动。
// ------------------------------------------------------------------

(function() {
    var ScriptName = "CodeNameSelect";
    function execute() {

        Type.registerNamespace('Kevin.Controls');

        $CodeNameSelect = Kevin.Controls.CodeNameSelect = function(element) {

            Kevin.Controls.CodeNameSelect.initializeBase(this, [element]);
            this._elmentContainer = null;
            this._txtCode = $get(element.id + "_txtCode");
            this._imgSelect = $get(element.id + "_imgSelect");
            this._btnSelect = null;
            this._txtSpan = $get(element.id + "_Span");
            this._txtSpan.style.display = 'none';
            this._txtCodeKeyDownHandler = null;
            //            this._clientStateField = null;
            //            this._clientState = null;
            this._CallbackID = null;
            // Path to the web service, or null if a page method
            this._servicePath = null;

            // Name of the web method
            this._serviceMethod = null;

            // User/page specific context provided to the web method
            this._contextKey = null;
            this._Value = null;
            this._ReadOnly = false;
            this._autoComplete = false;
            // Whether or not the the user/page specific context should be used
            this._useContextKey = false;
            this._minimumPrefixLength = 2;
            this._completionSetCount = 10;
            this._completionInterval = 1000;
            this._completionListElementID = null;
            this._completionListElement = null;
            this._completionListElementMaxHeight = 200;
            this._textColor = 'windowtext';
            this._textBackground = 'window';
            this._popupBehavior = null;
            this._popupBehaviorHiddenHandler = null;
            this._onShowJson = null;
            this._onHideJson = null;
            this._onWindowShowJson = null;
            this._onWindowHideJson = null;
            this._timer = null;
            this._cache = null;
            this._currentPrefix = null;
            this._selectIndex = -1;
            this._focusHandler = null;
            this._blurHandler = null;
            this._bodyClickHandler = null;
            this._completionListBlurHandler = null;
            this._keyDownHandler = null;
            this._mouseDownHandler = null;
            this._mouseUpHandler = null;
            this._mouseOverHandler = null;
            this._tickHandler = null;
            this._enableCaching = true;
            this._flyoutHasFocus = false;
            this._textBoxHasFocus = false;
            this._completionListCssClass = null;
            this._completionListItemCssClass = null;
            this._highlightedItemCssClass = null;
            this._CssClass = "CodeNameSelect";
            this._DialogCssClass = null;
            this._DialogDataListCssClass = null;
            this._delimiterCharacters = null;
            this._firstRowSelected = true;
            this._showOnlyCurrentWordInCompletionListItem = false;
            // WebRequest object returned from WebServiceProxy.invoke
            this._nameControlID = null;
            this._onSelectedComplete = null;
            this._webRequest = null;
            this._EnabledUserChangeText = false;
            this._ParentControlClientID = "";
            this._ParentControlClientValueMethod = "";
            //-----------------------------------------------------------------------------------------
            this._CodeNameWindow = null; //PopUp a Modal Window form to query and select the code
            this._CodeNameWindowForm = null;
            this._CodeNameWindowForm_Input = null;
            this._CodeNameWindowForm_Button = null;
            this._CodeNameWindowForm_Close = null;
            this._CodeNameWindowForm_Title = null;
            this._CodeNameWindowForm_TitleText = null;
            this._Animation = null;
            //this._CreateElement = null;
            this._divDataListInPopup = null;
            this._pageIndex = 1;
            this._elementWidth = 120;
            //-----------------------------------------------------------------------------------------
            //多项选择时使用
            this._mutiSelecte = false; //是否启用多项选择
            this._selectedItemList = null; //保存已选择的项 [{"Code":"","Name":""}]
            //-----------------------------------------------------------------------------------------

            this._btnCodeSearch$deleget = { click: Function.createDelegate(this, this._btnCodeSearchClick) }

            this._dialogTableCells$deleget = {
                mouseover: Function.createDelegate(this, this._dialogTableCellsMouseover),
                mouseout: Function.createDelegate(this, this._dialogTableCellsMouseout),
                click: Function.createDelegate(this, this._dialogTableCellsOnClick)
            }

            this._divPager$delegate = {
                click: Function.createDelegate(this, this._divPagerOnClick)
            }
            this.txtCodeSearch = null;
        }

        $CodeNameSelect.prototype = {

            initialize: function() {

                $CodeNameSelect.callBaseMethod(this, 'initialize');

                _txtCodeKeyDownHandler = Function.createDelegate(this, this._txtCodeKeyDown);
                _txtCodeOnBlurHandler = Function.createDelegate(this, this._txtCodeBlur);
                _txtCodeOnfocusHandler = Function.createDelegate(this, this._txtCodeFocus);
                _imgSelectClickHandler = Function.createDelegate(this, this._imgSelectClick);
                _CodeNameWindowFormInitHandler = Function.createDelegate(this, this._BuildDialog);
                _CodeNameWindowFormBlurHandler = Function.createDelegate(this, this._onCodeNameWindowFormBlur);
                _CodeNameWindowHiddenHandler = Function.createDelegate(this, this._codeNameWindownHidden);
                _CodeNameWindowForm_CloseClickHandler = Function.createDelegate(this, this._CodeNameWindowForm_CloseClick);
                _btnCodeSearchClickHandler = Function.createDelegate(this, this._btnCodeSearchClick)
                _tableCellsOnClickHandler = Function.createDelegate(this, this._dialogTableCellsOnClick);


                //this.get_element().style.width = this._elementWidth;

                /**/
                if (this._mutiSelecte) {
                    this._elmentContainer = $common.createElementFromTemplate({
                        nodeName: "div",
                        cssClasses: ["elementContainer"]
                    }, this.get_element());


                    this._elmentContainer.appendChild(this._txtCode);
                }

                //this._txtCode.style.width = $common.getBounds(this._elmentContainer).width - 21;
                $addHandler(this._txtCode, "keydown", _txtCodeKeyDownHandler);
                $addHandler(this._txtCode, "blur", _txtCodeOnBlurHandler);
                $addHandler(this._txtCode, "focus", _txtCodeOnfocusHandler);
                //$addHandler(this._imgSelect, "click", _imgSelectClickHandler);
                $common.setVisible(this._imgSelect, false);
                $common.addCssClasses(this.get_element(), [this._CssClass]);

                this._btnSelect = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["btnSelect"]
                }, this.get_element());

                //this._btnSelect = document.createElement("div");
                this._txtCode.parentNode.insertBefore(this._btnSelect, this._txtCode.nextSibling);

                $addHandler(this._btnSelect, "click", _imgSelectClickHandler);

                var element = this._txtCode;

                this._selectedItemList = new Array();

                this.initializeTextBox(this._txtCode); //初始化代码框，若有赋值则现在 get && set 代码名称

                //------------------------------------------------------------
                // 当控件为ReadOnly时，隐藏Textbox，并用span来显示数据
                // 席吉波 2011-01-12  start
                if (this._ReadOnly) {
                    this._txtCode.style.display = 'none';
                    this._txtSpan.style.display = '';
                    this._btnSelect.style.display = 'none';
                    //由于调用webservice需要时间，在此赋值并不妥当，会出现只能获取Code值
                    //故而在调用完成之后再赋值
                    //this._txtSpan.innerHTML = this._txtCode.value;
                    return;
                }
                // 席吉波 2011-01-12 end
                //------------------------------------------------------------

                if (this._autoComplete) {
                    this._popupBehaviorHiddenHandler = Function.createDelegate(this, this._popupHidden);
                    this._tickHandler = Function.createDelegate(this, this._onTimerTick);
                    this._focusHandler = Function.createDelegate(this, this._onGotFocus);
                    this._blurHandler = Function.createDelegate(this, this._onLostFocus);
                    this._keyDownHandler = Function.createDelegate(this, this._onKeyDown);
                    this._mouseDownHandler = Function.createDelegate(this, this._onListMouseDown);
                    this._mouseUpHandler = Function.createDelegate(this, this._onListMouseUp);
                    this._mouseOverHandler = Function.createDelegate(this, this._onListMouseOver);
                    this._completionListBlurHandler = Function.createDelegate(this, this._onCompletionListBlur);
                    this._bodyClickHandler = Function.createDelegate(this, this._onCompletionListBlur);

                    //this._tickHandler = Function.createDelegate(this, this._onTimerTick);
                    this._timer = new Sys.Timer();
                    this.initializeTimer(this._timer);
                    if (this._completionListElement == null) {
                        this._completionListElement = document.createElement('div');
                        this._completionListElement.id = this.get_element().id + '_completionListElem'; //element.id + '_completionListElem';
                        //this._completionListElementID= element.id + '_completionListElem';

                        // Safari styles the element incorrectly if it's added to the desired location
                        if (Sys.Browser.agent === Sys.Browser.Safari) {
                            document.body.appendChild(this._completionListElement);
                        } else {
                            element.parentNode.insertBefore(this._completionListElement, element.nextSibling);
                        }
                    }

                    this.initializeCompletionList(this._completionListElement); //初始化AutocompletionList

                    this._popupBehavior = $create(Sys.Extended.UI.PopupBehavior,
                    { 'id': this.get_element().id + 'PopupBehavior', 'parentElement': element, "positioningMode": Sys.Extended.UI.PositioningMode.BottomLeft }
                    , null, null, this._completionListElement);
                    this._popupBehavior.add_hidden(this._popupBehaviorHiddenHandler);
                }

                //this._BuildDialog();
                this._buildTopDialog();
                $addHandler(this._CodeNameWindowForm, "blur", _CodeNameWindowFormBlurHandler);
                var windowID = this.get_element().id + new Date().toLocaleTimeString() + new Date().getMilliseconds().toString() + 'CodeNameWindownPopupBehavior'; //
                if (!$get(windowID)) {
                    this._CodeNameWindow = $create(Sys.Extended.UI.PopupBehavior,
                        { 'id': windowID, 'parentElement': this._btnSelect, "positioningMode": Sys.Extended.UI.PositioningMode.BottomLeft }
                        , null, null, this._CodeNameWindowForm);
                    this._CodeNameWindow.add_hidden(_CodeNameWindowHiddenHandler);
                }

            },

            dispose: function() {
                $clearHandlers(this.get_element());
                $CodeNameSelect.callBaseMethod(this, 'dispose');
            },
            initializeTimer: function(timer) {

                timer.set_interval(this._completionInterval);
                timer.add_tick(this._tickHandler);
            },
            _CreateElement: function(targName, properties) {
                var el = document.createElement(targName);
                for (var key in properties) {
                    el.setAttribute(key, properties[key]);
                }
                return el;
            },

            _dialogTableCellsMouseover: function(e) { },
            _dialogTableCellsMouseout: function(e) { },
            _dialogTableCellsOnClick: function(e) {
                var target = e.target;
                if (this._txtCode && target.parentNode.title) {
                    var obj = Sys.Serialization.JavaScriptSerializer.deserialize(target.parentNode.title);
                    this._txtCode.value = this._mergerCodeName(obj);
                    this.set_Value(obj.Code);
                    this._CodeNameWindow.hide();


                    this._createNewSelectedItem(obj); //如果是多项选择，此句代码才会被执行

                    this._onValueChanged(obj);
                    e.preventDefault(); //防止scrollBar位置改变 席吉波
                    this._txtCode.focus();
                    //add by Kevin Xi 2011-05-23

                    //调用代码选择完成后客户端需要执行的方法
                    if (this._onSelectedComplete != null) {
                        var strScript = this._onSelectedComplete + "(\"{Code:'" + obj.Code + "',Name:'" + obj.Name + "'}\");"
                        eval(strScript);
                    }

                }
            },
            _mergerCodeName: function(obj) {
                return obj.Name + "(" + obj.Code + ")";
            },
            initializeCompletionList: function(element) {


                if (this._completionListCssClass) {
                    Sys.UI.DomElement.addCssClass(element, this._completionListCssClass);
                } else {
                    var completionListStyle = element.style;
                    completionListStyle.textAlign = 'left';
                    completionListStyle.visibility = 'hidden';
                    completionListStyle.cursor = 'default';
                    completionListStyle.listStyle = 'none';
                    completionListStyle.padding = '0px';
                    completionListStyle.margin = '0px! important';
                    if (Sys.Browser.agent === Sys.Browser.Safari) {
                        completionListStyle.border = 'solid 1px gray';
                        completionListStyle.backgroundColor = 'white';
                        completionListStyle.color = 'black';
                    } else {
                        completionListStyle.border = 'solid 1px buttonshadow';
                        completionListStyle.backgroundColor = this._textBackground;
                        completionListStyle.color = this._textColor;
                    }
                }
                $addHandler(element, "mousedown", this._mouseDownHandler);
                $addHandler(element, "mouseup", this._mouseUpHandler);
                $addHandler(element, "mouseover", this._mouseOverHandler);
                $addHandler(element, "blur", this._completionListBlurHandler);
                $addHandler(document.body, 'click', this._bodyClickHandler);
            },
            _currentCompletionWord: function() {
                var element = this._txtCode;
                var elementValue = element.value;
                var word = elementValue;

                if (this.get_isMultiWord()) {
                    var startIndex = this._getCurrentWordStartIndex();
                    var endIndex = this._getCurrentWordEndIndex(startIndex);

                    if (endIndex <= startIndex) {
                        word = elementValue.substring(startIndex);
                    } else {
                        word = elementValue.substring(startIndex, endIndex);
                    }
                }

                return word;
            },
            _BuildDialog: function() {
                var divID = "dialog_" + this.get_element().id;
                //*
                if ($get(divID)) {
                    $get(divID).parentNode.removeChild($get(divID));
                    //document.body.removeChild($get(divID));
                    // return;
                }
                //*/

                this._CodeNameWindowForm = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: [this._DialogCssClass],
                    properties: {
                        id: divID,
                        "display": "none"
                    }
                }, document.body); //document.body
                /*
                this._CodeNameWindowForm = top.document.createElement("div");
                this._CodeNameWindowForm.id = divID;
                this._CodeNameWindowForm.style.display="none";
                this._CodeNameWindowForm.attributes["class"] = this._DialogCssClass;
                window.top.document.body.appendChild(this._CodeNameWindowForm);
                //*/
                this._CodeNameWindowForm.style.width = "400px";
                this._CodeNameWindowForm.style.zIndex = 10000;
                this._CodeNameWindowForm_Title = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["title"],
                    properties: {
                        id: "dialog_title_" + divID
                    }
                }, this._CodeNameWindowForm);
                this._CodeNameWindowForm_Title.style.cursor = "move";

                var div_dialog_title_info = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["info"],
                    properties: {
                        id: "div_dialog_title_info_" + divID

                    }
                }, this._CodeNameWindowForm_Title);
                div_dialog_title_info.innerHTML = this._CodeNameWindowForm_TitleText;
                this._CodeNameWindowForm_Close = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["ico"],
                    properties: {
                        id: "div_dialog_title_close_" + divID

                    }
                }, this._CodeNameWindowForm_Title);
                //div_dialog_title_close.innerHTML = "X";var div_dialog_title_close =
                var dialog_content = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["content"],
                    properties: {
                        id: "dialog_content_" + divID

                    }
                }, this._CodeNameWindowForm);
                //click: Function.createDelegate(this, this._btnCodeSearchClick)
                dialog_content.style.height = "320px";
                this.txtCodeSearch = $common.createElementFromTemplate({
                    nodeName: "input",
                    cssClasses: ["inputText"],
                    properties: { type: "text", id: "txtCodeSearch_" + divID }
                }, dialog_content);
                this.txtCodeSearch.style.width = "80%";

                var btnSearch = $common.createElementFromTemplate({
                    nodeName: "input",
                    cssClasses: ["btnSelect"],
                    events: this._btnCodeSearch$deleget,
                    properties: { type: "button", id: "btnSearch_" + divID, value: " " }
                }, dialog_content);

                var div_hr = $common.createElementFromTemplate({
                    nodeName: "div",
                    properties: { type: "button", id: "div_hr" + divID }
                }, dialog_content);

                div_hr.innerHTML = "<hr/>";

                this._divDataListInPopup = $common.createElementFromTemplate({
                    nodeName: "div",
                    events: this._dialogTableCells$deleget,
                    properties: {
                        id: "div_dialog_conten" + divID,
                        styles: [{ "scroll": "auto"}]
                    }
                }, dialog_content);
                this._divDataListInPopup.innerHTML = "结果列表";

                //this._CodeNameWindow.add_hidden(this._popupBehaviorHiddenHandler);
                /*
                this._CodeNameWindow = $create(Sys.Extended.UI.ModalPopupBehavior,
                { "DropShadow": false,
                "PopupControlID": this._CodeNameWindowForm.id, //div_dialog.id,
                "PopupDragHandleControlID": dialog_title.id,
                "id": "ModalPopupBehavior" + this.get_element().id,
                "BackgroundCssClass": "modalBackground",
                "repositionMode": 2,
                "OkControlID": div_dialog_title_close.id,
                "isIE6": true,
                "z-index": 10001
                }, null, null, this._imgSelect);
                //this._CodeNameWindow.style.zIndex = 10001;
                this._CodeNameWindow.hide();
                //*/
                $addHandler(btnSearch, "click", _btnCodeSearchClickHandler);
                $addHandler(this._CodeNameWindowForm_Close, "click", _CodeNameWindowForm_CloseClickHandler);
                $create(Sys.Extended.UI.FloatingBehavior, { "id": divID + new Date().toLocaleTimeString() + "FloatingBehavior", "handle": this._CodeNameWindowForm_Title }, null, null, this._CodeNameWindowForm);

            }, //_BuildDialog
            _buildTopDialog: function() {
                var divID = "dialog_" + this.get_element().id;
                //*
                if ($get(divID)) {
                    $get(divID).parentNode.removeChild($get(divID));
                    //document.body.removeChild($get(divID));
                    // return;
                }
                //*/
                /*
                this._CodeNameWindowForm = CreateElement({
                nodeName: "div",
                cssClasses: [this._DialogCssClass],
                properties: {
                id: divID,
                "display": "none"
                }
                },window.top.document.body)
                //*/
                //*
                this._CodeNameWindowForm = document.createElement("div");
                this._CodeNameWindowForm.id = divID;
                this._CodeNameWindowForm.style.display = "none";
                //this._CodeNameWindowForm.attributes["class"] = this._DialogCssClass;
                $common.addCssClasses(this._CodeNameWindowForm, [this._DialogCssClass]);
                //window.top.document.body.appendChild(this._CodeNameWindowForm);
                //window.top.document.body.appendChild
                //*/
                this._CodeNameWindowForm.style.width = "400px";
                this._CodeNameWindowForm_Title = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["title"],
                    properties: {
                        id: "dialog_title_" + divID
                    }
                }, this._CodeNameWindowForm);
                this._CodeNameWindowForm_Title.style.cursor = "move";

                var div_dialog_title_info = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["info"],
                    properties: {
                        id: "div_dialog_title_info_" + divID

                    }
                }, this._CodeNameWindowForm_Title);
                div_dialog_title_info.innerHTML = this._CodeNameWindowForm_TitleText;
                this._CodeNameWindowForm_Close = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["ico"],
                    properties: {
                        id: "div_dialog_title_close_" + divID

                    }
                }, this._CodeNameWindowForm_Title);
                //div_dialog_title_close.innerHTML = "X";var div_dialog_title_close =
                var dialog_content = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["content"],
                    properties: {
                        id: "dialog_content_" + divID

                    }
                }, this._CodeNameWindowForm);
                //click: Function.createDelegate(this, this._btnCodeSearchClick)
                dialog_content.style.height = "320px";
                this.txtCodeSearch = $common.createElementFromTemplate({
                    nodeName: "input",
                    cssClasses: ["inputText"],
                    properties: { type: "text", id: "txtCodeSearch_" + divID }
                }, dialog_content);
                this.txtCodeSearch.style.width = "80%";

                var btnSearch = $common.createElementFromTemplate({
                    nodeName: "input",
                    cssClasses: ["btnSelect"],
                    events: this._btnCodeSearch$deleget,
                    properties: { type: "button", id: "btnSearch_" + divID, value: " 查询 " }
                }, dialog_content);

                var div_hr = $common.createElementFromTemplate({
                    nodeName: "div",
                    properties: { type: "button", id: "div_hr" + divID }
                }, dialog_content);

                div_hr.innerHTML = "<hr/>";

                this._divDataListInPopup = $common.createElementFromTemplate({
                    nodeName: "div",
                    events: this._dialogTableCells$deleget,
                    properties: {
                        id: "div_dialog_conten" + divID,
                        styles: [{ "scroll": "auto"}]
                    }
                }, dialog_content);
                this._divDataListInPopup.innerHTML = "结果列表";

                //this._CodeNameWindow.add_hidden(this._popupBehaviorHiddenHandler);
                /*
                this._CodeNameWindow = $create(Sys.Extended.UI.ModalPopupBehavior,
                { "DropShadow": false,
                "PopupControlID": this._CodeNameWindowForm.id, //div_dialog.id,
                "PopupDragHandleControlID": dialog_title.id,
                "id": "ModalPopupBehavior" + this.get_element().id,
                "BackgroundCssClass": "modalBackground",
                "repositionMode": 2,
                "OkControlID": div_dialog_title_close.id,
                "isIE6": true,
                "z-index": 10001
                }, null, null, this._imgSelect);
                //this._CodeNameWindow.style.zIndex = 10001;
                this._CodeNameWindow.hide();
                //*/
                document.body.appendChild(this._CodeNameWindowForm);
                $addHandler(btnSearch, "click", _btnCodeSearchClickHandler);
                $addHandler(this._CodeNameWindowForm_Close, "click", _CodeNameWindowForm_CloseClickHandler);
                $create(Sys.Extended.UI.FloatingBehavior, { "id": divID + new Date().toLocaleTimeString() + "FloatingBehavior", "handle": this._CodeNameWindowForm_Title }, null, null, this._CodeNameWindowForm);


            }, //end _buildTopDialog
            _imgSelectClick: function() {
                if (this._CodeNameWindow != null && this._CodeNameWindowForm != null) {

                    this._CodeNameWindowForm.style.zIndex = 10000;

                    if (!this._mutiSelecte) {
                        var codeName = Sys.Serialization.JavaScriptSerializer.deserialize(this._clientStateField.value);
                        if (codeName[0].Name.length > 0) {
                            this.txtCodeSearch.value = codeName[0].Name;
                        }
                        else {
                            this.txtCodeSearch.value = this._txtCode.value;
                        }
                    }
                    else {
                        this.txtCodeSearch.value = this._txtCode.value;
                    }

                    this._invoke1(1);

                    this._CodeNameWindow.show();
                }
            },
            _CodeNameWindowForm_CloseClick: function() {
                this._CodeNameWindow.hide();
            },
            _divPagerOnClick: function(e) {
                var target = e.target;
                if (target && target.tagName == 'A') {
                    this._invoke1(target.innerHTML);
                    this._pageIndex = target.innerHTML;
                }

            },
            _onMethodComplete1: function(result, context) {
                this._webRequest = null; // clear out our saved WebRequest object

                if (this._divDataListInPopup) {
                    this._divDataListInPopup.innerHTML = "";
                    var DataList = Sys.Serialization.JavaScriptSerializer.deserialize(result);

                    var table = "<table class='" + this._DialogDataListCssClass + "' width='100%'><tr><th align='center' style='width:20%'>代码</th><th align='center'>名称</th></tr>";
                    var pageCount = 0;
                    var rowIndex = 0;
                    for (var d in DataList) {
                        var dataRow = "<tr {4}><td title='{0}'><a href='#'>{1}<a></td><td title='{3}'><a href='#'>{2}<a></td></tr>";

                        if (DataList[d].Code == 'PAGE_COUNT') {
                            pageCount = DataList[d].Name;
                            break;
                        }

                        rowIndex = rowIndex + 1;

                        dataRow = String.format(dataRow,
                                        Sys.Serialization.JavaScriptSerializer.serialize(DataList[d]),
                                        DataList[d].Code,
                                        DataList[d].Name,
                                        Sys.Serialization.JavaScriptSerializer.serialize(DataList[d]),
                                        rowIndex % 2 == 0 ? "class='AlternatingRow'" : "class='NormalRow'"
                                    );
                        table = table + dataRow;

                    }
                    table += "</table>";

                    this._divDataListInPopup.innerHTML = table;


                    //------------------------------------------------------------------------------------------------------
                    //Pager
                    var div_pager = $common.createElementFromTemplate({
                        nodeName: "div",
                        events: this._divPager$delegate
                    }, this._divDataListInPopup);


                    var strA = "<a href='#' style='border:1px solid #DDD;background:#F2F2F2;text-decoration:none;margin:1px;'>{0}<a/>";
                    var strB = "<font color='red'><b>{0}</b></font>";
                    var a_list = "";
                    a_list += "总页数(" + pageCount + ") ";
                    var cpage = this._pageIndex;

                    if (pageCount <= 10) {        //总页数小于十页 
                        for (count = 1; count <= pageCount; count++) {
                            a_list += (count != cpage) ? String.format(strA, count) : String.format(strB, count);
                        }
                    }
                    if (pageCount > 10) {        //总页数大于十页 
                        if (parseInt((cpage - 1) / 10) == 0) {
                            for (count = 1; count <= 10; count++) {
                                a_list += (count != cpage) ? String.format(strA, count) : String.format(strB, count);
                            }
                            a_list += String.format(strA, count);
                        }
                        else if (parseInt((cpage - 1) / 10) == parseInt(pageCount / 10)) {
                            a_list += String.format(strA, (parseInt((cpage - 1) / 10) * 10));
                            for (count = parseInt(pageCount / 10) * 10 + 1; count <= pageCount; count++) {
                                a_list += (count != cpage) ? String.format(strA, count) : String.format(strB, count);
                            }
                        }
                        else {
                            a_list += String.format(strA, (parseInt((cpage - 1) / 10) * 10));
                            for (count = parseInt((cpage - 1) / 10) * 10 + 1; count <= parseInt((cpage - 1) / 10) * 10 + 10; count++) {
                                a_list += (count != cpage) ? String.format(strA, count) : String.format(strB, count);
                            }
                            a_list += String.format(strA, count);
                        }
                    }

                    div_pager.innerHTML = a_list;
                    //pager end
                    //------------------------------------------------------------------------------------------------------
                }
            }, //_onMethodComplete1
            _onMethodFailed1: function(err, response, context) {
                this._webRequest = null; // clear out our saved WebRequest object 
                if (this._divDataListInPopup) {
                    this._divDataListInPopup.innerHTML = "";
                }

            },
            _btnCodeSearchClick: function() {
                this._invoke1(1);
                this._pageIndex = 1;
            },
            _buildParams: function (code,pageSize,pageIndex) {
                var params = null;
                params = { Code: code, count: pageSize, indexNumber: pageIndex, code: code, pageSize: pageSize, pageIndex: pageIndex };
                if (this._ParentControlClientID != "") {
                    if (this._ParentControlClientValueMethod != "") {
                        params.ParentValue = eval(this._ParentControlClientValueMethod + "('" + this._ParentControlClientID + "')");
                    }
                    else {
                        params.ParentValue = eval("_getControlValue('" + this._ParentControlClientID + "')");
                    }
                }
                /*
                else {
                    params = { Code: this.txtCodeSearch.value, count: 10, indexNumber: pageIndex, code: this.txtCodeSearch.value, pageSize: 10, pageIndex: pageIndex };
                }
                //*/
                return params;
            },
            _invoke1: function (pageIndex) {
                if (this._servicePath && this._serviceMethod) {
                    var params = this._buildParams(this.txtCodeSearch.value,10, pageIndex);
                    if (this._webRequest) {
                        // abort the previous web service call if we 
                        // are issuing a new one and the previous one is 
                        // active.
                        this._webRequest.get_executor().abort();
                        this._webRequest = null;

                    }
                    this._pageIndex = pageIndex;
                    //this.setClientStateNull();
                    this._webRequest = Sys.Net.WebServiceProxy.invoke(this.get_servicePath(), this.get_serviceMethod(), false, params,
                                                        Function.createDelegate(this, this._onMethodComplete1),
                                                        Function.createDelegate(this, this._onMethodFailed1),
                                                        null);
                }
            },

            initializeTextBox: function(element) {

                element.autocomplete = "off";

                if (this._mutiSelecte) {

                    $common.addCssClasses(this.get_element(), ["mutiSelect"]);

                    var codeList = Sys.Serialization.JavaScriptSerializer.deserialize(this._clientStateField.value);

                    for (var index in codeList) {
                        if (codeList[index].Name) {
                            this._createNewSelectedItem(codeList[index]);
                        }
                        else {
                            document.getElementsByTagName
                            var v_code = codeList[index].Code;
                            //this._invokeSingle(null,v_code)
                            //sleep(this._completionInterval);
                            //setTimeout(Function.createDelegate(this,function(){this._invokeSingle(null,v_code);}),(parseInt(index)+1)*this._completionInterval);
                            var para = { "code": v_code };
                            setTimeout(Function.createDelegate(this, Function.createCallback(this._invokeSingle, para)), (parseInt(index) + 1) * this._completionInterval);
                        }
                    }

                    return;
                }

                if (this.get_Value()) {

                    this._txtCode.value = this._Value;
                    if (this._txtCode.value.trim().endsWith(")")) {
                        this._txtSpan.innerHTML = this._txtCode.value;
                        this._onValueChanged();
                        return;
                    }
                    this._invokeSingle(null, { "code": this._txtCode.value });
                }



            },
            _updateAuto: function(prefixText, completionItems, cacheResults) {
                if (cacheResults && true) {
                    if (!this._cache) {
                        this._cache = {};
                    }
                    this._cache[prefixText] = completionItems;
                }

                if ((!this._textBoxHasFocus) || (prefixText != this._currentCompletionWord()) || completionItems == null) {
                    this._hideCompletionList();
                    return;
                }

                var DataList = Sys.Serialization.JavaScriptSerializer.deserialize(completionItems)

                if (DataList.length > 1) {
                    this._completionListElement.innerHTML = '';
                    this._selectIndex = -1;
                    var _firstChild = null;
                    var text = null;
                    var value = null;

                    for (var i = 0; i < DataList.length - 1; i++) {
                        // Create the item                
                        var itemElement = null;
                        if (this._completionListElementID) {
                            // the completion element has been created by the user and li won't necessarily work
                            itemElement = document.createElement('div');
                        } else {
                            itemElement = document.createElement('li');
                        }

                        // set the first child if it is null
                        if (_firstChild == null) {
                            _firstChild = itemElement;
                        }

                        // Get the text/value for the item
                        try {
                            var item = DataList[i];
                            text = item.Name;
                            value = item.Code;

                        } catch (ex) {
                            text = DataList[i];
                            value = DataList[i];
                        }


                        var optionText = text + "(" + value + ")"; //this._showOnlyCurrentWordInCompletionListItem ? text : this._getTextWithInsertedWord(text);
                        itemElement.innerHTML = "<font>" + optionText + "</font>"; //.appendChild(document.createTextNode(optionText));
                        itemElement._value = item.Code;
                        itemElement._text = item.Name;
                        itemElement.__item = '';

                        if (this._completionListItemCssClass) {
                            Sys.UI.DomElement.addCssClass(itemElement, this._completionListItemCssClass);
                        } else {
                            var itemElementStyle = itemElement.style;
                            itemElementStyle.padding = '0px';
                            itemElementStyle.textAlign = 'left';
                            itemElementStyle.textOverflow = 'ellipsis';
                            itemElementStyle.width = "100%";
                            // workaround for safari since normal colors do not
                            // show well there.
                            if (Sys.Browser.agent === Sys.Browser.Safari) {
                                itemElementStyle.backgroundColor = 'white';
                                itemElementStyle.color = 'black';
                            } else {
                                itemElementStyle.backgroundColor = this._textBackground;
                                itemElementStyle.color = this._textColor;
                            }
                        }
                        this._completionListElement.appendChild(itemElement);
                    }
                    var elementBounds = $common.getBounds(this._txtCode);
                    this._completionListElement.style.width = Math.max(1, elementBounds.width - 2) + 'px';

                    //this._completionListElement.style.height=this._completionListElementMaxHeight+'px';//Math.min(this._completionListElement.style.height,this._completionListElementMaxHeight)+'px';

                    this._completionListElement.scrollTop = 0;

                    this.raisePopulated(Sys.EventArgs.Empty);

                    var eventArgs = new Sys.CancelEventArgs();
                    this.raiseShowing(eventArgs);
                    if (!eventArgs.get_cancel()) {
                        this.showPopup();
                        // Check if the first Row is to be selected by default and if yes highlight it and updated selectIndex.
                        if (this._firstRowSelected && (_firstChild != null)) {
                            this._highlightItem(_firstChild);
                            this._selectIndex = 0;
                        }
                    }
                } else {
                    this._hideCompletionList();
                }

            },
            _onMethodComplete_Auto: function(result, context) {
                this._webRequest = null; // clear out our saved WebRequest object    
                this._updateAuto(context, result, /* cacheResults */true);
            },
            _onMethodFailed_Auto: function(err, response, context) {
                this._webRequest = null;
            },
            _onTimerTick: function(sender, eventArgs) {

                // turn off the timer until another key is pressed.
                this._timer.set_enabled(false);

                if (this._servicePath && this._serviceMethod) {
                    var text = this._currentCompletionWord();

                    if (text.trim().length < this._minimumPrefixLength && !this._mutiSelecte) {
                        this._currentPrefix = null;
                        this._updateAuto('', null, /* cacheResults */false);
                        var state = {
                            Code: "",
                            Name: ""
                        };
                        this._clientStateField.value = Sys.Serialization.JavaScriptSerializer.serialize(new Array(state))
                        return;
                    }
                    // there is new content in the textbox or the textbox is empty but the min prefix length is 0
                    if ((this._currentPrefix !== text) || ((text == "") && (this._minimumPrefixLength == 0))) {
                        this._currentPrefix = text;
                        if ((text != "") && this._cache && this._cache[text]) {
                            this._updateAuto(text, this._cache[text], /* cacheResults */false); //根据录入的关键字取出缓存中客户需要的完整数据
                            return;
                        }
                        // Raise the populating event and optionally cancel the web service invocation
                        var eventArgs = new Sys.CancelEventArgs();
                        this.raisePopulating(eventArgs);
                        if (eventArgs.get_cancel()) {
                            return;
                        }

                        var params = this._buildParams(this._currentPrefix, this._completionSetCount,1); // { Code: this._currentPrefix, count: this._completionSetCount, indexNumber: 1, code: this._currentPrefix, pageSize: this._completionSetCount, pageIndex: 1 };
                        if (this._useContextKey) {
                            params.contextKey = this._contextKey;
                        }

                        if (this._webRequest) {

                            this._webRequest.get_executor().abort();
                            this._webRequest = null;
                        }
                        // Invoke the web service
                        this._webRequest = Sys.Net.WebServiceProxy.invoke(this.get_servicePath(), this.get_serviceMethod(), false, params,
                                                    Function.createDelegate(this, this._onMethodComplete_Auto),
                                                    Function.createDelegate(this, this._onMethodFailed_Auto),
                                                    text);
                        $common.updateFormToRefreshATDeviceBuffer();
                    }
                }
            },
            _getCursorIndex: function() {
                return this.get_element().selectionStart;
            },

            _getCurrentWordStartIndex: function() {
                var element = this.get_element();
                var elementText = element.value.substring(0, this._getCursorIndex());

                var index = 0;
                var lastIndex = -1;

                for (var i = 0; i < this._delimiterCharacters.length; ++i) {
                    var curIndex = elementText.lastIndexOf(this._delimiterCharacters.charAt(i));
                    if (curIndex > lastIndex) {
                        lastIndex = curIndex;
                    }
                }

                index = lastIndex;
                if (index >= this._getCursorIndex()) {
                    index = 0;
                }

                return index < 0 ? 0 : index + 1;
            },

            _getCurrentWordEndIndex: function(wordStartIndex) {
                var element = this.get_element();
                var elementText = element.value.substring(wordStartIndex);
                var index = 0;

                for (var i = 0; i < this._delimiterCharacters.length; ++i) {
                    var curIndex = elementText.indexOf(this._delimiterCharacters.charAt(i));
                    if (curIndex > 0 && (curIndex < index || index == 0)) {
                        index = curIndex;
                    }
                }

                return index <= 0 ? element.value.length : index + wordStartIndex;
            },

            get_isMultiWord: function() {

                return (this._delimiterCharacters != null) && (this._delimiterCharacters != '');
            },

            _getTextWithInsertedWord: function(wordToInsert) {
                var text = wordToInsert;
                var replaceIndex = 0;
                var element = this.get_element();
                var originalText = element.value;

                if (this.get_isMultiWord()) {
                    var startIndex = this._getCurrentWordStartIndex();
                    var endIndex = this._getCurrentWordEndIndex(startIndex);
                    var prefix = '';
                    var suffix = '';

                    if (startIndex > 0) {
                        prefix = originalText.substring(0, startIndex);
                    }
                    if (endIndex > startIndex) {
                        suffix = originalText.substring(endIndex);
                    }

                    text = prefix + wordToInsert + suffix;
                }

                return text;
            },
            _hideCompletionList: function() {

                var eventArgs = new Sys.CancelEventArgs();
                this.raiseHiding(eventArgs);
                if (eventArgs.get_cancel()) {
                    return;
                }

                // Actually hide the popup
                this.hidePopup();
            },
            _txtCodeKeyDown: function(ev) {

                if (this._timer) {
                    this._timer.set_enabled(false);
                }

                if (this._txtCode.value.trim().length < this._minimumPrefixLength) {
                    //ev.preventDefault();
                    //return;                    
                }

                var k = ev.keyCode ? ev.keyCode : ev.rawEvent.keyCode;
                if (k === Sys.UI.Key.enter) {

                    if (this._selectIndex >= 0) {
                        this._setText(this._completionListElement.childNodes[this._selectIndex]);
                        ev.preventDefault();
                        return;
                    } else {
                        this.hidePopup();
                        return;
                    }
                    /*
                    if (this._txtCode.value != "" && !this._txtCode.value.endsWith(")")) {

                        this._invokeSingle();

                        //ev.preventDefault(); //防止回车时页面submit
                    }
                    else {
                    var state = {
                    Code: "",
                    Name: ""
                    };
                    this._clientStateField.value = Sys.Serialization.JavaScriptSerializer.serialize(state)
                    }
                    */
                }
                else if (k === Sys.UI.Key.esc) {
                    this._hideCompletionList();
                    ev.preventDefault();
                }
                else if (k === Sys.UI.Key.up) {
                    if (this._selectIndex > 0) {
                        this._selectIndex--;
                        this._handleScroll(this._completionListElement.childNodes[this._selectIndex], this._selectIndex);
                        this._highlightItem(this._completionListElement.childNodes[this._selectIndex]);
                        ev.stopPropagation();
                        ev.preventDefault();
                    }
                }
                else if (k === Sys.UI.Key.down) {
                    if (this._selectIndex < (this._completionListElement.childNodes.length - 1)) {
                        this._selectIndex++;
                        this._handleScroll(this._completionListElement.childNodes[this._selectIndex], this._selectIndex);
                        this._highlightItem(this._completionListElement.childNodes[this._selectIndex]);
                        ev.stopPropagation();
                        ev.preventDefault();
                    }
                }
                else if (k === Sys.UI.Key.tab) {
                    if (this._selectIndex !== -1) {
                        this._setText(this._completionListElement.childNodes[this._selectIndex]);
                    }
                }
                else {
                    if (this._timer) {
                        this._timer.set_enabled(true);
                    }
                }
            },
            _txtCodeBlur: function(e) {

                //在多项选择情况下，不处理该事件
                if (this._mutiSelecte) return;

                if (this._txtCode.value != "" && !this._txtCode.value.endsWith(")")) {
                    this._invokeSingle(null, { "code": this._txtCode.value });
                    //ev.preventDefault(); //防止回车时页面submit
                }
                else {
                    if (this._txtCode.value == "") {
                        //return true; //Added 2010-06-22 
                        var state = {
                            Code: "",
                            Name: ""
                        };
                        this._clientStateField.value = Sys.Serialization.JavaScriptSerializer.serialize(new Array(state));
                    }
                    else {
                        //为了能让用户手动更改text信息，特此更改
                        if (this._EnabledUserChangeText) {
                            this._onValueChanged(null);
                        }
                    }
                }
            },
            _txtCodeFocus: function(e) {
                this._textBoxHasFocus = true;
                if (this._flyoutHasFocus) {
                    // hide the flyout now that the focus is back on the textbox
                    this._hideCompletionList();
                }
                if ((this._minimumPrefixLength == 0) && (!this._txtCode.value)) {
                    this._timer.set_enabled(true);
                    // only start the timer if the minimumprefixlength is 0
                    // since we would like to retrieve results even if
                    // the user has not entered any text and the textbox is empty.
                }
            },
            _setText: function(item) {
                var text = (item && item.firstChild) ? item.firstChild.nodeValue : null;
                this._timer.set_enabled(false);

                var newText = item._text;
                var newValue = item._value;

                this._txtCode.value = newText + "(" + newValue + ")";
                var state = { Code: newValue, Name: newText };

                this._clientStateField.value = Sys.Serialization.JavaScriptSerializer.serialize(new Array(state));
                this.raiseItemSelected(new Kevin.Controls.AutoCompleteItemEventArgs(item, text, item ? item._value : null));

                //Added By Kevin Xi 2011-05-23
                /*
                if (this._nameControlID != null) {
                $get(this._nameControlID).value = newText;
                }
                //*/
                //调用代码完成后客户端需要执行的方法
                if (this._onSelectedComplete != null) {
                    var strScript = this._onSelectedComplete + "(\"{Code:'" + state.Code + "',Name:'" + state.Name + "'}\");"
                    eval(strScript);
                }

                this._currentPrefix = this._currentCompletionWord();
                this._hideCompletionList();

                //多项选择的话下面会被执行
                this._createNewSelectedItem(state);
            },
            _update: function(prefixText, completionItems, cacheResults) {
                var codeName = Sys.Serialization.JavaScriptSerializer.deserialize(completionItems);
                if (codeName.length > 0) {
                    this._txtCode.value = codeName[0].Name + "(" + codeName[0].Code + ")";
                    this._txtSpan.innerHTML = this._txtCode.value;
                    this.set_Value(this._txtCode.value);
                    this._onValueChanged(codeName[0]);
                    //Added By 席吉波 2011-08-04
                    //调用代码完成后客户端需要执行的方法
                    if (this._onSelectedComplete != null) {
                        var strScript = this._onSelectedComplete + "(\"{Code:'" + codeName[0].Code + "',Name:'" + codeName[0].Name + "'}\");"
                        eval(strScript);
                    }
                    //如果是多项选择的话 下面会被执行
                    this._createNewSelectedItem(codeName[0]);
                }

            },

            _onMethodComplete: function(result, context) {
                this._webRequest = null; // clear out our saved WebRequest object
                this._update(context, result, /* cacheResults */true);

            },
            _onMethodFailed: function(err, response, context) {
                this._webRequest = null;
            },
            _invokeSingle: function(e, context) {

                if (this._servicePath && this._serviceMethod) {
                    //--------------------------------------------------------------------------
                    //这里在firefox，IE，Google浏览器中接受到的参数都不一致，在此做如下特殊处理
                    var code = "";
                    if (e != null && typeof (e) == "object") {
                        code = e.code;
                    }
                    else {
                        code = context.code;
                    }
                    //-------------------------------------------------------------------------    
                    var params = this._buildParams(code,1,1);// { Code: code, count: 1, indexNumber: 1, code: code, pageSize: 1, pageIndex: 1 };
                    if (this._webRequest) {
                        // abort the previous web service call if we 
                        // are issuing a new one and the previous one is 
                        // active.
                        this._webRequest.get_executor().abort();
                        this._webRequest = null;
                    }
                    this.setClientStateNull();
                    this._webRequest = Sys.Net.WebServiceProxy.invoke(this.get_servicePath(), this.get_serviceMethod(), false, params,
                                            Function.createDelegate(this, this._onMethodComplete),
                                            Function.createDelegate(this, this._onMethodFailed),
                                            null);
                }
            },
            _onValueChanged: function(obj) {

                //多项选择时保存 this._selectedItemList 中的数据
                if (this._mutiSelecte) {
                    this._clientStateField.value = Sys.Serialization.JavaScriptSerializer.serialize(this._selectedItemList);
                    return;
                }

                if (obj) {
                    this._clientStateField.value = Sys.Serialization.JavaScriptSerializer.serialize(new Array(obj)); //is._txtCode.value;
                } //Added 2010-06-02, 以便明细选择料件时，控件可获得相应的值
                if (this._txtCode.value.endsWith(')')) {
                    var codename = this._txtCode.value.trim();
                    var code = codename.substr(codename.lastIndexOf("(") + 1, codename.length - 3);
                    var name = codename.substr(0, codename.lastIndexOf("("));

                    if (code.endsWith(')')) {
                        code = code.substr(0, code.length - 1);
                    }

                    var state = {
                        Code: code,
                        Name: name
                    };
                    this._clientStateField.value = Sys.Serialization.JavaScriptSerializer.serialize(new Array(state));
                }
                else {
                    var state = {
                        Code: "",
                        Name: ""
                    };
                    this._clientStateField.value = Sys.Serialization.JavaScriptSerializer.serialize(new Array(state));
                }


            },
            _createNewSelectedItem: function(obj) {
                if (this._mutiSelecte == false) { return; }

                //--------------------------------------------------------------
                //如果是多重选择 2011-12-16 席吉波
                var idPrefix = this.get_element().id;
                for (var index in this._selectedItemList) {
                    if (this._selectedItemList[index].Code == obj.Code) {
                        this._txtCode.value = "";
                        $common.removeCssClasses($get(idPrefix + obj.Code), ["itemContains"]);
                        $common.removeCssClasses($get(idPrefix + obj.Code), ["itemSelected"]);
                        $common.addCssClasses($get(idPrefix + obj.Code), ["itemContains"]);
                        setTimeout(function() { $common.removeCssClasses($get(idPrefix + obj.Code), ["itemContains"]); }, 2000);
                        return;
                    }
                }

                this._selectedItemList.push(obj);

                var item = $common.createElementFromTemplate({
                    nodeName: "span",
                    properties: {
                        id: idPrefix + obj.Code
                    },
                    cssClasses: ["item"]
                }, null);
                item.innerHTML = obj.Name + "(" + obj.Code + "); ";

                $addHandler(item, "click", Function.createDelegate(this, Function.createCallback(this._itemClick, { "id": item.id, "code": obj.Code })));
                $addHandler(item, "keydown", Function.createDelegate(this, Function.createCallback(this._selectedItemKeydwon, item.id)));
                $addHandler(item, "mouseover", Function.createDelegate(this, function() { $common.addCssClasses(item, ["itemHover"]); }));
                $addHandler(item, "mouseout", Function.createDelegate(this, function() { $common.removeCssClasses(item, ["itemHover"]); }));

                this.get_element().insertBefore(item, this._elmentContainer);

                this._txtCode.value = "";
                this._onValueChanged(obj);
                //-------------------------------------------------------------
            },
            showPopup: function() {

                this._popupBehavior.show();
                this.raiseShown(Sys.EventArgs.Empty);
            },
            hidePopup: function() {


                if (this._popupBehavior) {
                    this._popupBehavior.hide();
                } else {
                    this._popupHidden();
                }
            },
            _popupHidden: function() {

                this._completionListElement.innerHTML = '';
                this._selectIndex = -1;
                this._flyoutHasFocus = false;

                this.raiseHidden(Sys.EventArgs.Empty);
            },
            _codeNameWindownHidden: function() {

                this.raiseHidden(Sys.EventArgs.Empty);
            },
            _highlightItem: function(item) {

                var children = this._completionListElement.childNodes;

                // Unselect any previously highlighted item
                for (var i = 0; i < children.length; i++) {
                    var child = children[i];
                    if (child._highlighted) {
                        if (this._completionListItemCssClass) {
                            Sys.UI.DomElement.removeCssClass(child, this._highlightedItemCssClass);
                            Sys.UI.DomElement.addCssClass(child, this._completionListItemCssClass);
                        } else {
                            if (Sys.Browser.agent === Sys.Browser.Safari) {
                                child.style.backgroundColor = 'white';
                                child.style.color = 'black';
                            } else {
                                child.style.backgroundColor = this._textBackground;
                                child.style.color = this._textColor;
                            }
                        }
                        this.raiseItemOut(new Kevin.Controls.AutoCompleteItemEventArgs(child, child.firstChild.nodeValue, child._value));
                    }
                }

                // Highlight the new item
                if (this._highlightedItemCssClass) {
                    Sys.UI.DomElement.removeCssClass(item, this._completionListItemCssClass);
                    Sys.UI.DomElement.addCssClass(item, this._highlightedItemCssClass);
                } else {
                    if (Sys.Browser.agent === Sys.Browser.Safari) {
                        item.style.backgroundColor = 'lemonchiffon';
                    } else {
                        item.style.backgroundColor = 'highlight';
                        item.style.color = 'highlighttext';
                    }

                }
                item._highlighted = true;
                this.raiseItemOver(new Kevin.Controls.AutoCompleteItemEventArgs(item, item.firstChild.nodeValue, item._value));
            },
            _onCompletionListBlur: function(ev) {
                this._hideCompletionList();
            },
            _onCodeNameWindowFormBlur: function(ev) {
                this._CodeNameWindow.hidden();
            },
            _onListMouseDown: function(ev) {

                if (ev.target !== this._completionListElement) {
                    var tar = ev.target.nodeName;
                    if (tar == 'FONT') {

                        this._setText(ev.target.parentNode);
                        this._flyoutHasFocus = false;
                    }
                    else {
                        this._setText(ev.target);
                        this._flyoutHasFocus = false;
                    }
                } else { // focus is still on the flyout and we do not want to hide it
                    this._flyoutHasFocus = true;
                }
            },

            _onListMouseUp: function(ev) {

                try { this.get_element().focus(); } catch (e) { }
            },

            _onListMouseOver: function(ev) {

                var item = ev.target;
                if (item !== this._completionListElement) {
                    var children = this._completionListElement.childNodes;
                    // make sure the selected index is updated
                    for (var i = 0; i < children.length; ++i) {
                        if (item === children[i]) {
                            this._highlightItem(item);
                            this._selectIndex = i;
                            break;
                        }
                    }
                }
            },

            _onGotFocus: function(ev) {

                this._textBoxHasFocus = true;
                if (this._flyoutHasFocus) {
                    // hide the flyout now that the focus is back on the textbox
                    this._hideCompletionList();
                }
                if ((this._minimumPrefixLength == 0) && (!this.get_element().value)) {
                    this._timer.set_enabled(true);

                }
            },
            _handleScroll: function(element, index) {

                var flyout = this._completionListElement;
                var elemBounds = $common.getBounds(element);
                var numItems = this._completionListElement.childNodes.length;
                if (((elemBounds.height * index) - (flyout.clientHeight + flyout.scrollTop)) >= 0) {
                    // you need to scroll down
                    flyout.scrollTop += (((elemBounds.height * index) - (flyout.clientHeight + flyout.scrollTop)) + elemBounds.height);
                }
                if (((elemBounds.height * (numItems - (index + 1))) - (flyout.scrollHeight - flyout.scrollTop)) >= 0) {
                    // you need to scroll up
                    flyout.scrollTop -= (((elemBounds.height * (numItems - (index + 1))) - (flyout.scrollHeight - flyout.scrollTop)) + elemBounds.height);
                }

                if (flyout.scrollTop % elemBounds.height !== 0) {
                    if (((elemBounds.height * (index + 1)) - (flyout.clientHeight + flyout.scrollTop)) >= 0) {
                        // an element is partially displayed at the bottom
                        flyout.scrollTop -= (flyout.scrollTop % elemBounds.height);
                    } else { // an element is partially displayed on the top 
                        flyout.scrollTop += (elemBounds.height - (flyout.scrollTop % elemBounds.height));
                    }
                }

            },

            _handleFlyoutFocus: function() {
                /// <summary>
                /// Method to handle flyout focus if textbox loses focus.
                /// </summary>
                /// <returns />   
                if (!this._textBoxHasFocus) {
                    if (!this._flyoutHasFocus) {
                        if (this._webRequest) {
                            // abort the web service call if we are losing focus. no sense having it delay future web requests.
                            this._webRequest.get_executor().abort();
                            this._webRequest = null;
                        }
                        // the textbox lost focus and the flyout does not have it
                        this._hideCompletionList();
                    } else {
                        // keep the flyout around otherwise
                    }
                }
            },
            _onLostFocus: function() {

                this._textBoxHasFocus = false;
                this._timer.set_enabled(false);
                /* the rest of the onblur handling will be done in
                this method after a minor delay to ensure we do not close the flyout 
                if a user clicks on its scroll bars for example */
                window.setTimeout(Function.createDelegate(this, this._handleFlyoutFocus), 500);
            },
            _onKeyDown: function(ev) {

                // If textbox had focus on page load, _onGotFocus() would not have been called.
                // So if a user started typing, then focus is obviously on the textbox.
                this._textBoxHasFocus = true;

                this._timer.set_enabled(false);
                // the last key press occured so we need to "reset" the timer.
                var k = ev.keyCode ? ev.keyCode : ev.rawEvent.keyCode;
                if (k === Sys.UI.Key.esc) {
                    this._hideCompletionList();
                    ev.preventDefault();
                }
                else if (k === Sys.UI.Key.up) {
                    if (this._selectIndex > 0) {
                        this._selectIndex--;
                        this._handleScroll(this._completionListElement.childNodes[this._selectIndex], this._selectIndex);
                        this._highlightItem(this._completionListElement.childNodes[this._selectIndex]);
                        ev.stopPropagation();
                        ev.preventDefault();
                    }
                }
                else if (k === Sys.UI.Key.down) {
                    if (this._selectIndex < (this._completionListElement.childNodes.length - 1)) {
                        this._selectIndex++;
                        this._handleScroll(this._completionListElement.childNodes[this._selectIndex], this._selectIndex);
                        this._highlightItem(this._completionListElement.childNodes[this._selectIndex]);
                        ev.stopPropagation();
                        ev.preventDefault();
                    }
                }
                else if (k === Sys.UI.Key.enter) {
                    if (this._selectIndex !== -1) {
                        this._setText(this._completionListElement.childNodes[this._selectIndex]);
                        ev.preventDefault();
                    } else {
                        // close the popup
                        this.hidePopup();
                    }
                }
                else if (k === Sys.UI.Key.tab) {
                    if (this._selectIndex !== -1) {
                        this._setText(this._completionListElement.childNodes[this._selectIndex]);
                    }
                }
                else {
                    this._timer.set_enabled(true);
                    // start the timer to retrieve results since now it is an actual key
                }
            },
            _ReceiveServerData: function(result) {
                alert(result);
            },
            _onCallbackError: function(e) {
                alert("回调失败！" + e);
            },
            _onFocus: function(e) {
                //alert("_onFocus");
            },
            _onBlur: function(e) {
                //alert("_onBlur");
            },
            _itemClick: function(e, obj) {

                var classList = $get(obj.id).classList || $get(obj.id).className.split(' '); //此处为了兼容IE,FF,google浏览器

                for (var i in classList) {
                    if (classList[i] == "itemSelected") {

                        var tempList = new Array();
                        for (var index in this._selectedItemList) {
                            if (this._selectedItemList[index].Code != obj.code) {
                                tempList.push(this._selectedItemList[index]);
                            }
                        }
                        this._selectedItemList = tempList;

                        $common.removeElement($get(obj.id));
                        this._onValueChanged(null);

                        return;
                    }
                }

                for (var index in this._selectedItemList) {
                    $common.removeCssClasses($get(this.get_element().id + this._selectedItemList[index].Code), ["itemSelected"]);
                    $get(this.get_element().id + this._selectedItemList[index].Code).title = "";
                }

                var item = $get(obj.id);

                if (item) {
                    $common.addCssClasses(item, ["itemSelected"]);
                    item.title = "再点击一次删除";
                }
                // $addHandler($get(id),"keypress",Function.createDelegate(this,this._selectedItemKeydwon));

            },
            _selectedItemKeydwon: function(ev, id) {

                var classList = $get(id).classList;

                for (var i in classList) {
                    if (classList[i] == "itemSelected") return;
                }

                var _keyCode = ev.keyCode ? ev.keyCode : ev.rawEvent.keyCode;
                //var id = ev.id;
                //如果用户按下了esc 则取消选择，并移除keydown事件
                if (_keyCode === Sys.UI.Key.esc) {
                    $removeHandler($get(id), "keypress", ev["keypress"]);
                    $common.removeCssClasses($get(id), ["itemSelected"]);
                }
                //如果用户按下了删除键或退格键 则删除此项
                if (_keyCode === Sys.UI.Key.del || _keyCode === Sys.UI.Key.backspace) {

                    var tempList = new Array();
                    for (var index in this._selectedItemList) {
                        if (this._selectedItemList[index].Code != id.replace("item", "")) {
                            tempList.push(this._selectedItemList[index]);
                        }
                    }
                    this._selectedItemList = tempList;

                    $common.removeElement($get(id));
                }
            },
            getCodeNameFrom_txtCode: function() {
                if (this._txtCode.value.endsWith(')')) {
                    var codename = this._txtCode.value.trim();
                    var code = codename.substr(codename.lastIndexOf("(") + 1, codename.length);

                    var name = codename.substr(0, codename.lastIndexOf("("));

                    if (code.endsWith(')'))
                        code = code.substr(0, code.length - 1);

                    var state = {
                        Code: code,
                        Name: name
                    };
                    return state;
                }

                return {
                    Code: "",
                    Name: ""
                };
            },
            setClientStateNull: function() {
                var state = {
                    Code: "",
                    Name: ""
                };
                this._clientStateField.value = Sys.Serialization.JavaScriptSerializer.serialize(new Array(state));
            },
            saveClientState: function() {
                var codename = this._txtCode.value.trim();
                var code = codename.substr(codename.lastIndexOf("(") + 1, codename.length - 3);
                var name = codename.substr(0, codename.lastIndexOf("("));
                if (code.endsWith(')')) {
                    code = code.substr(0, code.length - 1);
                }
                var state = {
                    Code: code,
                    Name: name
                };
                //var state = this._txtCode.value;
                if (!this._mutiSelecte) {
                    //单项选择时
                    this._selectedItemList = new Array();
                    this._selectedItemList.push(state);
                    return Sys.Serialization.JavaScriptSerializer.serialize(this._selectedItemList);
                }
                else {
                    //多项选择时
                    return Sys.Serialization.JavaScriptSerializer.serialize(this._selectedItemList);
                }
                //return state;
            },
            loadClientState: function() {
                if (this._clientStateField.value == '' || this._clientStateField.value == 'undefined') {
                    return;
                }
                this._clientState = Sys.Serialization.JavaScriptSerializer.deserialize(this._clientStateField.value);
                //this._clientState = this._clientStateField.value;
            },

            get_serviceMethod: function() {

                return this._serviceMethod;
            },
            set_serviceMethod: function(value) {
                if (this._serviceMethod != value) {
                    this._serviceMethod = value;
                    this.raisePropertyChanged('serviceMethod');
                }
            },
            get_servicePath: function() {

                return this._servicePath;
            },
            set_servicePath: function(value) {
                if (this._servicePath != value) {
                    this._servicePath = value;
                    this.raisePropertyChanged('servicePath');
                }
            },
            get_autoComplete: function() {
                return this._autoComplete;
            },
            set_autoComplete: function(value) {
                if (this._autoComplete != value) {
                    this._autoComplete = value;
                    this.raisePropertyChanged('autoComplete');
                }
            },
            get_completionInterval: function() {
                return this._completionInterval;
            },
            set_completionInterval: function(value) {
                if (this._completionInterval != value) {
                    this._completionInterval = value;
                    this.raisePropertyChanged('completionInterval');
                }
            },
            get_contextKey: function() {

                return this._contextKey;
            },
            set_contextKey: function(value) {
                if (this._contextKey != value) {
                    this._contextKey = value;
                    this.set_useContextKey(true);
                    this.raisePropertyChanged('contextKey');
                }
            },

            get_useContextKey: function() {

                return this._useContextKey;
            },
            set_useContextKey: function(value) {
                if (this._useContextKey != value) {
                    this._useContextKey = value;
                    this.raisePropertyChanged('useContextKey');
                }
            },
            get_minimumPrefixLength: function() {

                return this._minimumPrefixLength;
            },
            set_minimumPrefixLength: function(value) {
                if (this._minimumPrefixLength != value) {
                    this._minimumPrefixLength = value;
                    this.raisePropertyChanged('minimumPrefixLength');
                }
            },
            get_CallbackID: function() {
                return this._CallbackID;
            },
            set_CallbackID: function(value) {
                this._CallbackID = value;
            },
            get_Value: function() {
                return this._Value;
            },
            set_Value: function(value) {
                if (this._Value != value) {
                    this._Value = value;
                    this.raisePropertyChanged('Value');
                }
            },
            get_ReadOnly: function() {
                return this._ReadOnly;
            },
            set_ReadOnly: function(value) {
                if (this._ReadOnly != value) {
                    this._ReadOnly = value;
                    this.raisePropertyChanged('ReadOnly');
                }
            },
            get_completionListCssClass: function() {

                return this._completionListCssClass;
            },
            set_completionListCssClass: function(value) {
                if (this._completionListCssClass != value) {
                    this._completionListCssClass = value;
                    this.raisePropertyChanged('completionListCssClass');
                }
            },

            get_completionListItemCssClass: function() {

                return this._completionListItemCssClass;
            },
            set_completionListItemCssClass: function(value) {
                if (this._completionListItemCssClass != value) {
                    this._completionListItemCssClass = value;
                    this.raisePropertyChanged('completionListItemCssClass');
                }
            },
            get_CodeNameWindowForm_TitleText: function() {
                return this._CodeNameWindowForm_TitleText;
            },
            set_CodeNameWindowForm_TitleText: function(value) {
                this._CodeNameWindowForm_TitleText = value;
            },
            get_highlightedItemCssClass: function() {

                return this._highlightedItemCssClass;
            },
            set_highlightedItemCssClass: function(value) {
                if (this._highlightedItemCssClass != value) {
                    this._highlightedItemCssClass = value;
                    this.raisePropertyChanged('highlightedItemCssClass');
                }
            },
            get_CssClass: function() {
                return this._CssClass;
            },
            set_CssClass: function(value) {
                this._CssClass = value;
            },
            get_DialogCssClass: function() {
                return this._DialogCssClass;
            },
            set_DialogCssClass: function(value) {
                this._DialogCssClass = value;
            },
            get_DialogDataListCssClass: function() {
                return this._DialogDataListCssClass;
            },
            set_DialogDataListCssClass: function(value) {
                this._DialogDataListCssClass = value;
            },
            get_completionSetCount: function() {

                return this._completionSetCount;
            },
            set_completionSetCount: function(value) {
                if (this._completionSetCount != value) {
                    this._completionSetCount = value;
                    this.raisePropertyChanged('completionSetCount');
                }
            },
            get_Text: function() { return ''; },
            set_Text: function(value) { },
            get_clientStateField: function() {
                return this._clientStateField;
            },
            set_clientStateField: function(value) {
                if (this._clientStateField != value) {
                    this._clientStateField = value;
                    this.raisePropertyChanged('clientStateField');
                }
            },
            add_populating: function(handler) {

                this.get_events().addHandler('populating', handler);
            },
            remove_populating: function(handler) {

                this.get_events().removeHandler('populating', handler);
            },
            raisePopulating: function(eventArgs) {


                var handler = this.get_events().getHandler('populating');
                if (handler) {
                    handler(this, eventArgs);
                }
            },

            add_populated: function(handler) {

                this.get_events().addHandler('populated', handler);
            },
            remove_populated: function(handler) {

                this.get_events().removeHandler('populated', handler);
            },
            raisePopulated: function(eventArgs) {

                var handler = this.get_events().getHandler('populated');
                if (handler) {
                    handler(this, eventArgs);
                }
            },
            get_onShow: function() {

                return this._onShowJson;
            },
            set_onShow: function(value) {

                this._onShowJson = value;
                this.raisePropertyChanged('onShow');
            },
            get_onHide: function() {

                return this._onHideJson;
            },
            set_onHide: function(value) {

                this._onHideJson = value;

                this.raisePropertyChanged('onHide');
            },
            get_onWindowShow: function() {

                return this._onWindowShowJson;
            },
            set_onWindowShow: function(value) {

                this._onWindowShowJson = value;
                this.raisePropertyChanged('onWindowShow');
            },
            get_onWindowHide: function() {

                return this._onWindowHideJson;
            },
            set_onWindowHide: function(value) {

                this._onWindowHideJson = value;

                this.raisePropertyChanged('onWindowHide');
            },
            get_nameControlID: function() {

                return this._nameControlID;
            },
            set_nameControlID: function(value) {

                this._nameControlID = value;

                this.raisePropertyChanged('nameControlID');
            },
            get_onSelectedComplete: function() {

                return this._onSelectedComplete;
            },
            set_onSelectedComplete: function(value) {

                this._onSelectedComplete = value;

                this.raisePropertyChanged('onSelectedComplete');
            },
            get_mutiSelecte: function() {
                return this._mutiSelecte;
            },
            set_mutiSelecte: function(value) {
                this._mutiSelecte = value;
            },
            get_ElementWidth: function() {
                return this._elementWidth;
            },
            set_ElementWidth: function(value) {
                this._elementWidth = value;
            },
            get_EnabledUserChangeText: function () {
                return this._EnabledUserChangeText;
            },
            set_EnabledUserChangeText: function (value) {
                this._EnabledUserChangeText = value;
            },
            get_ParentControlClientID: function () {
                return this._ParentControlClientID;
            },
            set_ParentControlClientID: function (value) {
                this._ParentControlClientID = value;
            },
            get_ParentControlClientValueMethod: function () {
                return this._ParentControlClientValueMethod;
            },
            set_ParentControlClientValueMethod: function (value) {
                this._ParentControlClientValueMethod = value;
            },
            add_showing: function (handler) {

                this.get_events().addHandler('showing', handler);
            },
            remove_showing: function(handler) {

                this.get_events().removeHandler('showing', handler);
            },
            raiseShowing: function(eventArgs) {


                var handler = this.get_events().getHandler('showing');
                if (handler) {
                    handler(this, eventArgs);
                }
            },

            add_shown: function(handler) {

                this.get_events().addHandler('shown', handler);
            },
            remove_shown: function(handler) {

                this.get_events().removeHandler('shown', handler);
            },
            raiseShown: function(eventArgs) {


                var handler = this.get_events().getHandler('shown');
                if (handler) {
                    handler(this, eventArgs);
                }
            },

            add_hiding: function(handler) {

                this.get_events().addHandler('hiding', handler);
            },
            remove_hiding: function(handler) {

                this.get_events().removeHandler('hiding', handler);
            },
            raiseHiding: function(eventArgs) {


                var handler = this.get_events().getHandler('hiding');
                if (handler) {
                    handler(this, eventArgs);
                }
            },

            add_hidden: function(handler) {

                this.get_events().addHandler('hidden', handler);
            },
            remove_hidden: function(handler) {

                this.get_events().removeHandler('hidden', handler);
            },
            raiseHidden: function(eventArgs) {

                var handler = this.get_events().getHandler('hidden');
                if (handler) {
                    handler(this, eventArgs);
                }
            },

            add_itemSelected: function(handler) {

                this.get_events().addHandler('itemSelected', handler);
            },
            remove_itemSelected: function(handler) {

                this.get_events().removeHandler('itemSelected', handler);
            },
            raiseItemSelected: function(eventArgs) {

                var handler = this.get_events().getHandler('itemSelected');
                if (handler) {
                    handler(this, eventArgs);
                }
            },

            add_itemOver: function(handler) {

                this.get_events().addHandler('itemOver', handler);
            },
            remove_itemOver: function(handler) {

                this.get_events().removeHandler('itemOver', handler);
            },
            raiseItemOver: function(eventArgs) {

                var handler = this.get_events().getHandler('itemOver');
                if (handler) {
                    handler(this, eventArgs);
                }
            },

            add_itemOut: function(handler) {

                this.get_events().addHandler('itemOut', handler);
            },
            remove_itemOut: function(handler) {

                this.get_events().removeHandler('itemOut', handler);
            },
            raiseItemOut: function(eventArgs) {


                var handler = this.get_events().getHandler('itemOut');
                if (handler) {
                    handler(this, eventArgs);
                }
            }
        }

        $CodeNameSelect.descriptor = {
            properties: [{ name: 'completionInterval', type: Number },
                    { name: 'completionList', isDomElement: true },
                    { name: 'completionListElementID', type: String },
                    { name: 'completionSetCount', type: Number },
                    { name: 'minimumPrefixLength', type: Number },
                    { name: 'serviceMethod', type: String },
                    { name: 'servicePath', type: String },
                    { name: 'enableCaching', type: Boolean },
                    { name: 'showOnlyCurrentWordInCompletionListItem', type: Boolean },
                    { name: 'Value', type: String },
                    { name: 'nameControlID', type: String },
                    { name: 'onSelectedComplete', type: String}]
        }

        $CodeNameSelect.registerClass('Kevin.Controls.CodeNameSelect', Sys.UI.Control, Sys.IDisposable);

        Kevin.Controls.AutoCompleteItemEventArgs = function(item, text, value) {

            Kevin.Controls.AutoCompleteItemEventArgs.initializeBase(this);

            this._item = item;
            this._text = text;
            this._value = (value !== undefined) ? value : null;
        }
        Kevin.Controls.AutoCompleteItemEventArgs.prototype = {
            get_item: function() {
                /// <value type="Sys.UI.DomElement" DomElement="true" mayBeNull="true">
                /// Item
                /// </value>
                return this._item;
            },
            set_item: function(value) {
                this._item = value;
            },

            get_text: function() {
                /// <value type="String" maybeNull="true">
                /// Text of the item
                /// </value>
                return this._text;
            },
            set_text: function(value) {
                this._text = value;
            },

            get_value: function() {
                /// <value type="String" maybeNull="true">
                /// Value of the item different from text if specifically returned by the webservice
                /// as autocomplete json text/value item(using AutoComplete.CreateAutoCompleteItem); otherwise same as text.
                /// </value>
                return this._value;
            },
            set_value: function(value) {
                this._value = value;
            }
        }
        Kevin.Controls.AutoCompleteItemEventArgs.registerClass('Kevin.Controls.AutoCompleteItemEventArgs', Sys.EventArgs);

    } //execute

    if (window.Sys && Sys.loader) {
        Sys.loader.registerScript(ScriptName, ["ExtendedModalPopup"], null, execute);

    }
    else {
        execute();
    }

})();